package com.gxuwz.medical.web.servlet;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gxuwz.medical.dao.ChronicInfoDao;
import com.gxuwz.medical.dao.ChronicdisDao;
import com.gxuwz.medical.dao.PersonDao;
import com.gxuwz.medical.dao.PolicyDao;
import com.gxuwz.medical.dao.RecordfreeDao;
import com.gxuwz.medical.dao.ReducttreatDao;
import com.gxuwz.medical.domain.chronicdis.Chronicdis;
import com.gxuwz.medical.domain.chronicinfo.ChronicInfo;
import com.gxuwz.medical.domain.chronicinfo.Recordfree;
import com.gxuwz.medical.domain.chronicinfo.Reducttreat;
import com.gxuwz.medical.domain.payment.Payment;
import com.gxuwz.medical.domain.person.Person;
import com.gxuwz.medical.domain.policy.Policy;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

/**
 * 慢性病档案管理控制模块
 * @author 演示
 *
 */
public  class ChronicInfoServlet extends BaseServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String m = req.getParameter("m");// 请求处理动作类型:list:显示列表；get：根据ID读取记录;input:新增数据;add:保存新记录；edit：更新记录
		String url = ERROR_PATH;
		try { 
			if ("list".equals(m)) {	
				url="/page/chronicinfo/chronicinfo_list.jsp";
			} else if ("input".equals(m)) {
				url="/page/chronicinfo/chronicinfo_add.jsp";
			} else if ("get".equals(m)) {
				url="/page/chronicinfo/chronicinfo_edit.jsp";			
			} else if ("add".equals(m)) {
				url = this.add(req, resp);
			}else if ("edit".equals(m)) {
				url = this.edit(req, resp);
			}else if ("del".equals(m)) {
				url = this.del(req, resp);
			}else if ("reductlist".equals(m)) {			
				url = "/page/reductreat/reductreat_list.jsp";
			}else if ("delreduct".equals(m)) {
				url = this.delreduct(req, resp);
			}else if ("givemoney".equals(m)) {
				url = this.givemoney(req, resp);
			}else if ("addreduct".equals(m)) {
				url = this.addreduct(req, resp);
			}else if ("inputreduct".equals(m)) {
				url ="/page/reductreat/reductreat_add.jsp";
			}else if ("reductprint".equals(m)) {
				url =this.reductprint(req,resp,null);
			}
			
			   process(req, resp, url);
		} catch (Exception e) {
			e.printStackTrace();
		}
		  

	}
	private String reductprint(HttpServletRequest req, HttpServletResponse resp,String id) throws RowsExceededException, WriteException, SQLException, IOException {
		// TODO Auto-generated method stub
		WritableWorkbook wwb = null;
		//插件可写入的excel工作表
		String fileName = "C://Users//pptf//Desktop//medical12//WebRoot//xls//reductprint.xls";
		File file = new File(fileName);
		if (!file.exists()) {
			file.createNewFile();
		}
		wwb =Workbook.createWorkbook(file);
		WritableSheet ws = wwb.createSheet("Test Shee 1", 0);
		Label chronicInfoId = new Label(0, 0, "慢病证号");
		Label treattime = new Label(1, 0, "就诊时间");
		Label money = new Label(2, 0, "治疗花费");
		Label freemoney = new Label(3, 0, "报销金额");
		Label hosId = new Label(4, 0, "医疗票单");
		ws.addCell(chronicInfoId);
		ws.addCell(treattime);
		ws.addCell(money);
		ws.addCell(freemoney);
		ws.addCell(hosId);
		ReducttreatDao dao=new ReducttreatDao();
		List<Reducttreat> list=null;
		Object[] params=new Object[1];
		if(id!=null) {
			params[0]=id;
			list=dao.queryOjects("select * from t_reducttreat where id=?", params);
		}
		else {
			params[0]=1;
			list=dao.queryOjects("select * from t_reducttreat where reductstatus=?", params);
		}
		int i=0;
	    for(Reducttreat r :list){
	    	String chronicInfoIdd=r.getChronicInfoId();
	    	String treattimee=r.getTreattime();
	    	String moneyy=""+r.getMoney();
	    	String freemoneyy=""+r.getFreemoney();
	    	String hosIdd=r.getHosId();
			Label chronicInfoId_i = new Label(0, i + 1, chronicInfoIdd);
			Label treattime_i = new Label(1, i + 1, treattimee);
			Label money_i = new Label(2, i + 1, moneyy);
			Label freemoney_i = new Label(3, i + 1, freemoneyy);
			Label hosId_i = new Label(4, i + 1, hosIdd);

			ws.addCell(chronicInfoId_i);
			ws.addCell(treattime_i);
			ws.addCell(money_i);
			ws.addCell(freemoney_i);
			ws.addCell(hosId_i);
			i++;
			
			}

	    wwb.write();
		// 关闭Excel工作簿对象
		System.out.println("数据导出成功!");
		wwb.close();
		
		return "/page/reductreat/reductreat_list.jsp";
		
	}


	private String delreduct(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub
		String id=req.getParameter("id");
		Object[] params=new Object[2];
		params[0]=id;
		ReducttreatDao dao=new ReducttreatDao();
		try {
			dao.editOrdelObject("delete from t_reducttreat where id=?", params);
			return "/page/reductreat/reductreat_list.jsp";
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/error.jsp";
	}


	/**
	 * 添加慢病档案
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	private String add(HttpServletRequest req,HttpServletResponse resp)throws Exception{
		 //1:获取慢病档案信息
		 String perscode=req.getParameter("perscode");
		 String persname=req.getParameter("persname");
		 String illcode=req.getParameter("illcode");
		 String starttime=req.getParameter("starttime");
		 String endtime=req.getParameter("endtime");
		 //从session对象中获取当前用户名称
		 String creator=(String)req.getSession().getAttribute("userName");
		 //开始检查核验
		 Object[] params=new Object[2];
		 params[0]=perscode;
		 params[1]=persname;
		 String sql="select * from t_person where perscode=? and persname=?";
		 PersonDao pdao=new PersonDao();
		 List<Person> plist=pdao.queryOjects(sql, params);
		 if(plist==null||plist.size()==0) {
			 req.setAttribute("error", "农合证号或姓名信息填写错误");
			 return "/error.jsp";
		 }
		 sql="select * from t_chronicInfo where perscode=? and illcode=?";
		 params=new Object[2];
		 params[0]=perscode;
		 params[1]=illcode;
		 System.out.println("perscode="+perscode+"illcode="+illcode);
		 ChronicInfoDao cDao=new ChronicInfoDao();
		 List<ChronicInfo> clist=cDao.queryOjects(sql, params);
		 if(clist!=null&&clist.size()!=0) {
			 req.setAttribute("error", "该慢性病已有登记证明，信息填写错误");
			 return "/error.jsp";
		 }
		 //2:实例化慢病证管理模块组件
		 ChronicInfo model=new ChronicInfo();
		 //3:将请求参数赋值给实例的成员属性
		 model.setChronicdis(new Chronicdis(illcode));
		 model.setPerson(new Person(perscode));
		 model.setStarttime(starttime);//慢病开始时间
		 model.setEndtime(endtime);//慢病结束时间
		 model.setCreator(creator);//建档人
		 model.setStatus("1");//档案状态：1表示正常
		 model.addChroInfo();
		 return "/page/chronicinfo/chronicinfo_list.jsp";
		
	}	
	private String addreduct(HttpServletRequest req,HttpServletResponse resp)throws Exception{
		 //1:获取慢病档案信息
		 String perscode=req.getParameter("perscode");
		 String persname=req.getParameter("persname");
		 String illcode=req.getParameter("illcode");
		 String treattime=req.getParameter("treattime");
		 String hosId=req.getParameter("hosId");
		 String money=req.getParameter("money");
		 String chronicInfoId="";
		 //开始检查核验
		 Object[] params=new Object[2];
		 params[0]=perscode;
		 params[1]=persname;
		 String sql="select * from t_person where perscode=? and persname=?";
		 PersonDao pdao=new PersonDao();
		 List<Person> plist=pdao.queryOjects(sql, params);
		 if(plist==null||plist.size()==0) {
			 req.setAttribute("error", "农合证号或姓名信息填写错误,或还未参合");
			 return "/error.jsp";
		 }
		 sql="select * from t_chronicInfo where perscode=? and illcode=?";
		 params=new Object[2];
		 params[0]=perscode;
		 params[1]=illcode;
		 System.out.println("perscode="+perscode+"illcode="+illcode);
		 ChronicInfoDao cDao=new ChronicInfoDao();
		 List<ChronicInfo> clist=cDao.queryOjects(sql, params);
		 if(clist==null||clist.size()==0) {
			 req.setAttribute("error", "没有相应的慢病证，不能申请");
			 return "/error.jsp";
		 }
		 chronicInfoId=clist.get(0).getId();
		 String starttime=clist.get(0).getStarttime();
		 String endtime=clist.get(0).getEndtime();
		 if(Long.valueOf(starttime.replaceAll("-",""))>Long.valueOf(treattime.replaceAll("-", ""))){ 
			//满足条件时表示：开始时间小于结束时间 
			 req.setAttribute("error", "就诊时间小于慢病证开始时间，不能申请");
			 return "/error.jsp";
			} 
		 if(Long.valueOf(endtime.replaceAll("-",""))<Long.valueOf(treattime.replaceAll("-", ""))){ 
				//满足条件时表示：开始时间小于结束时间 
				 req.setAttribute("error", "就诊时间大于慢病证结束时间，不能申请");
				 return "/error.jsp";
				} 
		 double freemoney=0;
		 int totalmoney=0;
		 double rate=0.5;
		 RecordfreeDao rdao=new RecordfreeDao();
		 params=new Object[1];
		 params[0]=perscode;
		 List<Recordfree> rlist=rdao.queryOjects("select * from t_recordfree where perscode=?", params);
		 if(rlist==null||rlist.size()==0) {
			 params=new Object[2];
			 params[0]=perscode;
			 params[1]=0;
			 rdao.editOrdelObject("insert into t_recordfree(perscode,freetotal)values(?,?)", params);
		 }
		 else {
			 totalmoney=rlist.get(0).getFreetotal();
		 }
		 int maxfree=0;
		 PolicyDao pldao=new PolicyDao();
		 params=new Object[1];
		 params[0]=treattime.substring(0, 4);
		 List<Policy> pllist=pldao.queryOjects("select * from t_policy where runyear=?", params);
		 if(pllist==null||pllist.size()==0) {
			 req.setAttribute("error", "不能报销该年度的，不能申请");
			 return "/error.jsp";
		 }
		 maxfree=(int)pllist.get(0).getMaxline();
		 ChronicdisDao chrondao=new ChronicdisDao();
		 params[0]=illcode;
		 List<Chronicdis> chronlist=chrondao.queryOjects("select * from t_chronicdis where illcode=?", params);
		 rate=chronlist.get(0).getRate();
		 Reducttreat model=new Reducttreat();
		 model.setChronicInfoId(chronicInfoId);
		 model.setHosId(hosId);
		 model.setMoney(Integer.valueOf(money));
         model.setReductstatus(0);
         model.setTreattime(treattime);
         double  num=Double.valueOf(money);
		 freemoney=num*rate;
		 int numm=maxfree-totalmoney;
		 int freelast=(int)freemoney;
		 if(freelast>numm) freelast=numm;
		 if(numm==0) {
			 req.setAttribute("error", "报销金额已达封顶线，不能申请");
			 return "/error.jsp"; 
		 }
		 model.setFreemoney(freelast);
		 model.addReducttreat();;
		 RecordfreeDao recdao=new RecordfreeDao();
		 params=new Object[2];
		 int total=freelast+totalmoney;
		 params[0]=total;
		 params[1]=perscode;
		 recdao.editOrdelObject("update t_recordfree set freetotal=? where perscode=?", params);
		 return "/page/reductreat/reductreat_list.jsp";
		
	}	
	private String givemoney(HttpServletRequest req,HttpServletResponse resp) throws RowsExceededException, WriteException, IOException {
		String flag=req.getParameter("flag");
		String id=req.getParameter("id");
		int reductstatus=Integer.valueOf(flag);
		Object[] params=new Object[2];
		params[0]=reductstatus;
		params[1]=id;
		ReducttreatDao dao=new ReducttreatDao();
		try {
			dao.editOrdelObject("update t_reducttreat set reductstatus=? where id=?", params);
			if(flag.equals("1")) {
				this.reductprint(req, resp, id);
			}
			return "/page/reductreat/reductreat_list.jsp";
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "/error.jsp";
	}
	private String edit(HttpServletRequest req,HttpServletResponse resp) {
		String id=req.getParameter("id");
		String starttime=req.getParameter("starttime");
		String endtime=req.getParameter("endtime");
		String sql="update t_chronicInfo set starttime=?,endtime=? where id=?";
		Object[] params=new Object[3];
		params[0]=starttime;
		params[1]=endtime;
		params[2]=id;
		ChronicInfoDao dao=new ChronicInfoDao();
		try {
			dao.editOrdelObject(sql, params);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/page/chronicinfo/chronicinfo_list.jsp";
	}
	private String del(HttpServletRequest req,HttpServletResponse resp) {
		String id=req.getParameter("id");
		String sql="delete from t_chronicInfo where id=?";
		Object[] params=new Object[1];
		params[0]=id;
		ChronicInfoDao dao=new ChronicInfoDao();
		try {
			dao.editOrdelObject(sql, params);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/page/chronicinfo/chronicinfo_list.jsp";
	}

}
